package com.xps.and.yuntong.Ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xps.and.yuntong.Data.bean1.ShortBean;
import com.xps.and.yuntong.Data.bean1.ShortVerification;
import com.xps.and.yuntong.Data.net.UserNetWorks;
import com.xps.and.yuntong.R;
import com.xps.and.yuntong.Utils.AppCommond;
import com.xps.and.yuntong.Utils.MD5Utils;
import com.xps.and.yuntong.Utils.RegularValidation;
import com.xps.and.yuntong.base.BaseActivity;
import com.jude.utils.JUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import rx.Subscriber;


/**
 * Created by administrator on 2017-12-09.
 */

public class RegistOneActivity extends BaseActivity implements View.OnClickListener {

    private ImageView iv_fanhui, iv_right, ivRedGou;
    private EditText etInputPhone, etYanZhengCode, etSheZhiPassword, etSheZhiPasswordAgain;
    private LinearLayout llRegistNextOne, ll_agree;
    private TextView tv_middle, tvGetCode;

    private int second = 60;

    private boolean flag_agree = false;
    private String md5Number;
    private String smsModel = "DRIVER_REGISTER";

    @Override
    protected int getLayout() {
        return R.layout.activity_regist_one;
    }

    @Override
    protected void setData() {

    }

    @Override
    protected void init(Bundle inBundle) {
        initView();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    private void initView() {

        iv_fanhui = (ImageView) findViewById(R.id.iv_fanhui);
        iv_right = (ImageView) findViewById(R.id.iv_right);
        iv_right.setVisibility(View.GONE);
        ivRedGou = (ImageView) findViewById(R.id.iv_red_gou);
        etInputPhone = (EditText) findViewById(R.id.et_input_phone1);
        etYanZhengCode = (EditText) findViewById(R.id.et_yanzheng_code);
        etSheZhiPassword = (EditText) findViewById(R.id.et_shezhi_password);
        etSheZhiPasswordAgain = (EditText) findViewById(R.id.et_shezhi_password_again);
        tv_middle = (TextView) findViewById(R.id.tv_middle);
        tv_middle.setText(R.string.register);
        tvGetCode = (TextView) findViewById(R.id.tv_get_code);
        llRegistNextOne = (LinearLayout) findViewById(R.id.ll_regist_next1);
        ll_agree = (LinearLayout) findViewById(R.id.ll_agree);

        tvGetCode.setOnClickListener(this);
        iv_fanhui.setOnClickListener(this);
        llRegistNextOne.setOnClickListener(this);
        ll_agree.setOnClickListener(this);
        ivRedGou.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.tv_get_code:
//                Intent intent = new Intent(RegistOneActivity.this, RegistTwoCeshiActivity.class);
//                startActivity(intent);
//                finish();
                if (!isNull(0)) return;
                md5Number = etInputPhone.getText().toString().substring(7, 11) + etInputPhone.getText().toString().substring(0, 3) + smsModel;
                String md5number1 = MD5Utils.MD5Encode(md5Number, "utf-8").toLowerCase();
                Log.e("md5number", md5Number);
                Log.e("md5number1", md5number1);
                tvGetCode.setEnabled(false);
                Log.e("111", isNull(0) + "");
                handler.postDelayed(runnable, 0);
                getShort(md5number1);

                Log.e("111", isNull(0) + "======");


                break;
            case R.id.ll_regist_next1:

                if (!ableGoNext()) return;
                if (!isNull(1)) return;
                getShortVerification();


                break;
            case R.id.ll_agree:
//                Intent intent1 = new Intent(RegistOneActivity.this, RegistThreeActivity.class);
//                startActivity(intent1);
                Intent xieyeintent = new Intent(RegistOneActivity.this, HelpXEActivity.class);
                startActivity(xieyeintent);
                break;

            case R.id.iv_fanhui:
//                Intent intent2 = new Intent(RegistOneActivity.this, RegistFourActivity.class);
//                startActivity(intent2);
                finish();
                break;
            case R.id.iv_red_gou:
                if (!flag_agree) {
                    flag_agree = true;
                    ivRedGou.setImageResource(R.drawable.red_yuan_sure);
                } else {
                    flag_agree = false;
                    ivRedGou.setImageResource(R.drawable.yuan_kongxin_kuang);
                }


                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
        unRegEventBus();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            second--;
            Message msg = handler.obtainMessage();
            if (second > 0) {
                msg.what = 0;
                handler.handleMessage(msg);
                handler.postDelayed(this, 1000);
            } else {
                msg.what = 1;
                handler.handleMessage(msg);
            }
        }
    };


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    tvGetCode.setText("重获" + "(" + second + "s)");
                    break;
                case 1:
                    second = 60;
                    tvGetCode.setText("重新获取");
                    tvGetCode.setEnabled(true);
                    this.removeCallbacks(runnable);
                    break;
            }
        }
    };


    private boolean isNull(int which) {
        if (which == 0) {
            if (TextUtils.isEmpty(etInputPhone.getText().toString())) {
                Toast.makeText(RegistOneActivity.this, "请输入手机号！", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!RegularValidation.isMobileNO(etInputPhone.getText().toString())) {
                Toast.makeText(RegistOneActivity.this, "请输入正确的手机号！", Toast.LENGTH_SHORT).show();
                return false;
            }

        } else {
            if (!etSheZhiPassword.getText().toString().trim().equals(etSheZhiPasswordAgain.getText().toString().trim())) {
                Toast.makeText(RegistOneActivity.this, "两次密码输入不一致，请重新输入！", Toast.LENGTH_SHORT).show();
                return false;
            } else if (etSheZhiPassword.getText().toString().trim().length() < 6) {
                Toast.makeText(RegistOneActivity.this, "密码不能少于6位", Toast.LENGTH_SHORT).show();
                return false;
            }

        }
        return true;
    }

    boolean ableGoNext() {
        if (TextUtils.isEmpty(etInputPhone.getText().toString())) {
            JUtils.Toast("请输入手机号");
            return false;
        }
        else if (TextUtils.isEmpty(etYanZhengCode.getText().toString())) {
            JUtils.Toast("请输入验证码");
            return false;
        } else if (TextUtils.isEmpty(etSheZhiPassword.getText().toString())) {
            JUtils.Toast("请输入密码");
            return false;
        } else if (TextUtils.isEmpty(etSheZhiPasswordAgain.getText().toString())) {
            JUtils.Toast("请再次输入密码");
            return false;
        } else if (flag_agree == false) {
            JUtils.Toast("请先阅读并《同意服务员合作协议》");
            return false;
        }
        return true;
    }


    void getShort(String md5number) {
        UserNetWorks.getShort(etInputPhone.getText().toString().trim(), smsModel, md5number, new Subscriber<ShortBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                JUtils.Toast("发送失败");
            }

            @Override
            public void onNext(ShortBean shortBean) {
                if (shortBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(shortBean.getReturn_msg());
                } else if (shortBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(shortBean.getReturn_msg());
                }
            }
        });
    }

    void getShortVerification() {
        UserNetWorks.getShortVerification(etInputPhone.getText().toString().trim(), smsModel, etYanZhengCode.getText().toString().trim(), new Subscriber<ShortVerification>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                e.printStackTrace();
                JUtils.Toast("发送失败");
            }

            @Override
            public void onNext(ShortVerification shortVerification) {

                if (shortVerification.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(shortVerification.getReturn_msg());
                    SharedPreferences sp = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd = sp.edit();
                    spEd.putString("mobile_phone", etInputPhone.getText().toString().trim());
                    spEd.putString("password", etSheZhiPassword.getText().toString().trim());
                    spEd.commit();
                    Intent intent = new Intent(RegistOneActivity.this, RegistTwoCeshiActivity.class);
                    startActivity(intent);
                } else if (shortVerification.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(shortVerification.getReturn_msg());
                }
            }
        });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AppCommond a) {
        if (!AppCommond.check(a)) return;
        for (String activityName : a.getAcNameList()) {
            if(activityName.contains(getClass().getSimpleName())){
                unRegEventBus();
                finish();
                break;
            }
        }
    }

    void unRegEventBus() {
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }


}
